#
# page navigation helpers for SimpleLog
# by S. Brent Faulkner (brentf@unwwwired.net) - Aug 25, 2007
#

class Site #:nodoc:
  class << self #:nodoc:
    # Generate a navigation link within a list element
    def nav_linked(title, url, is_current = false)
      nav = %Q(<li#{' id="current"' if is_current}>)
      nav += %Q(<a href="#{url}">#{title}</a>)
      nav += %Q(</li>)
    end
    # Generate a series of navigation links within list elements for the main blog page and a provided collection of pages
    def nav_pages_linked(pages, id = 'nav_main', home = 'Home')
      nav = ''
      nav += %Q(<div id="#{id}"><ul>) if id != ''
      nav += nav_linked(home, Site.full_url, is_home_page) if home != ''
      pages.each do |p|
        nav += nav_linked(p.title, Site.link_to_page(p.permalink), page_is('pages/'+p.permalink))
      end unless pages.nil?
      nav += %Q(</ul></div>) if id != ''
      nav
    end
  end
end

module SimpleNav #:nodoc:
  def self.included(base)
    base.class_eval do
      class << self
        # The inherited hook is used to preserve the lazy controller loading mechanism.
        def inherited_with_page_loader(sub_class)
          inherited_without_page_loader(sub_class)
          return unless sub_class.name == 'ApplicationController'
          begin
            sub_class.class_eval do
              # Load active pages into array for PostController, PageController and for unknown requests in ApplicationController
              def preload_pages
                return unless %w(post page).include?(self.controller_name) or self.action_name == 'handle_unknown_request'
                @pages = Page.find(:all, :conditions => 'is_active = true')
              end
              # Use before filter to load page array
              before_filter :preload_pages
            end
          rescue
            # Don't get in the way of the framework
          end
        end
        alias_method_chain :inherited, :page_loader
      end
    end
  end
end

ActionController::Base.class_eval do
  include SimpleNav
end
